package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.metagurukul.metagranth.service.QuestionService;
import com.metagurukul.metagranth.vo.MetaData;
import com.metagurukul.metagranth.vo.Tag;

/**
 * Servlet implementation class SearchQuestionByTagServlet This servlet performs
 * the functionality of searching thw questions associated with each tag posted
 * or added so far
 * 
 * @author team MetaGranth
 * 
 */
public class SearchQuestionByTagServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SearchQuestionByTagServlet() {
		super();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * this function is called when all those questions are to be retrieved with which the selected tags are 
	 * associated. 
	 * will return the list of all such questions
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if(session.getAttribute("userId")!=null){
		try {
			
		int tagId = Integer.parseInt(request.getParameter("tagFilterId"));
		Tag tag = new Tag();
		//sets the tagName of selected tag for which questionList is to be retrieved
		tag.setTagid(tagId);
		ArrayList<MetaData> questionList = new ArrayList<MetaData>();
		RequestDispatcher rd = null;
		//Gets the questionList by calling searchByTag function in the QuestionService Service layer.
		questionList = QuestionService.searchByTag(tag);
		request.setAttribute("metaDataList", questionList);
		rd = request.getRequestDispatcher("search-result.jsp");
		rd.forward(request, response);
		} catch (Exception exception) {
			request.setAttribute("errormsg", exception.getMessage());
			request.getRequestDispatcher("errorPage.jsp").forward(request,response);
		}}else{
			response.sendRedirect("index.jsp");
		}

	}

}
